/* 
  getState 用来获取reducer中的state的
  dispatch 用来触发reducer执行的
  subscribe 用来存储那些回调函数的
            存储的这些回调函数是要在数据更新之后再去执行的

*/
export function createStore(reducer, fn) {
  let state;
  let callbacks = [];// 存储subscribe接受的回调函数
  function getState() {
    return state
  }
  function dispatch(action) {
    console.log(action)
    state = reducer(state, action)//数据更新
    callbacks.forEach(f => {
      f()
    })
  }
  dispatch({ type: "@@redux/INITa.l.n.j.m.z" })
  function subscribe(f) {
    if (!callbacks.includes(f)) {
      callbacks.push(f)
    }
    return function clear() {
      // 这个回调函数负责 把填进来的f从callbacks中移除掉
      callbacks = callbacks.filter(item => item != f)
    }

  }

  if (typeof fn == 'function') {
    let newCreateStore = fn(createStore)
    return newCreateStore(reducer)
  }
  return {
    getState,
    dispatch,
    subscribe
  }
}
export function combineReducers(obj) {
  // obj:{A:reducer,B:reducer2}
  return function rootReducer(rootState, action) {
    // debugger
    rootState = rootState || {}// {A:{count:100},B:{color:'red'}}
    Object.keys(obj).forEach(key => {
      rootState[key] = obj[key](rootState[key], action)
    })
    return { ...rootState }
  }
}


/* 
  applyMiddleware 就是产生了一个新的state
  这个新state 是根据原始产生的那个state结合中间件产生dispatch 产生的
  applyMiddleware目的就是用中间件的dispatch 来替换原始那个disptch


*/

export function compose(...fs) {
  let first = fs.shift()
  return function f(...arg) {
    return fs.reduce((prev, cur) => {
      return cur(prev)
    }, first(...arg))
  }
}
export function applyMiddleware(...middle) {
  // middle ==> [thunk,qqq]
  return function fn(createStore) {
    // createStore 就是原始的redux提供的方法
    return function newCreateStore(reducer) {
      let store = createStore(reducer) // {getState,subscribe,dispatch}
      let temp = middle.map(mid => mid(store))
      let newDispatch = compose(...temp)(store.dispatch)
      return {
        ...store,
        dispatch: newDispatch
        // dispatch: function () {
        //   //这个函数应该通过 中间件产生
        //   console.log('applyM 产生的dis')
        // }
      }
    }
  }
}


export function applyMiddleware_one(middle) {
  // middle ==> thunk  store=>nect=>action
  return function fn(createStore) {
    // createStore 就是原始的redux提供的方法
    return function newCreateStore(reducer) {
      let store = createStore(reducer) // {getState,subscribe,dispatch}
      let temp = middle(store)
      let newDispatch = temp(store.dispatch)
      return {
        ...store,
        dispatch: newDispatch
        // dispatch: function () {
        //   //这个函数应该通过 中间件产生
        //   console.log('applyM 产生的dis')
        // }
      }
    }
  }
}